package com.atguigu.newmvc.controller;

import com.atguigu.newmvc.pojo.Employee;
import com.atguigu.newmvc.service.EmpService;
import com.atguigu.newmvc.utils.R;
import com.atguigu.newmvc.vo.req.AddVo;
import com.atguigu.newmvc.vo.req.UpdateVo;
import com.atguigu.newmvc.vo.resp.EmpRespVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Tag(name = "员工管理")
public class EmpController {
    @Autowired
    private EmpService empService;

    @GetMapping("/getEmp/{id}")
    @Operation(summary = "查看单个员工")
    public R getEmp(@PathVariable Integer id){
//        int i = 10/0;
       Employee employee= empService.getEmpById(id);
        EmpRespVo empRespVo = new EmpRespVo();
        BeanUtils.copyProperties(employee,empRespVo);
       return R.ok(employee);
    }

    @PostMapping("/addEmp")
    @Operation(summary = "增加一个员工")
    public R addEmp(@RequestBody @Valid AddVo addVo){
        Employee employee = new Employee();
        BeanUtils.copyProperties(addVo,employee);
        empService.addEmp(employee);
        return R.ok();
    }

    @DeleteMapping("/delEmp/{id}")
    @Operation(summary = "删除一个员工")
    public R delEmp(@PathVariable Integer id){
        empService.delEmp(id);
        return R.ok();
    }

    @PutMapping("/updateEmp")
    @Operation(summary = "修改一个员工")
    public R updateEmp(@RequestBody @Valid UpdateVo updateVo){
        Employee employee = new Employee();
        BeanUtils.copyProperties(updateVo,employee);
        empService.updateEmp(employee);
        return R.ok();
    }

    @GetMapping("/getAllEmp")
    @Operation(summary = "查看所有员工")
    public R<List<EmpRespVo>> getAllEmp() {
        List<Employee> employeeList = empService.getAllEmp();
        ArrayList<EmpRespVo> empRespVoList = new ArrayList<>();
        employeeList.forEach(employee -> {
            EmpRespVo empRespVo = new EmpRespVo();
            BeanUtils.copyProperties(employee, empRespVo);
            empRespVoList.add(empRespVo);
        });
        return R.ok(empRespVoList);
    }
}
